// 获取url 参数
export function getUrlKey (name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || ['', ''])[1].replace(/\+/g, '%20')) || null
}

// 获取地址栏中hash参数
export function getQueryString (name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  var r = window.location.hash.substr(1).match(reg)
  if (r != null) return unescape(r[2])
  return null
}
// 是否为数组
export const isArray = function (value) {
  if (typeof Array.isArray === 'function') {
    return Array.isArray(value)
  } else {
    return Object.prototype.toString.call(value) === '[object Array]'
  }
}

// 表单序列化
export const serialize = data => {
  const list = []
  Object.keys(data).forEach(ele => {
    list.push(`${ele}=${data[ele]}`)
  })
  return list.join('&')
}

// 获取对象类型
export const getObjType = obj => {
  var toString = Object.prototype.toString
  var map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object'
  }
  if (obj instanceof Element) {
    return 'element'
  }
  return map[toString.call(obj)]
}

/**
 * 对象深拷贝
 */
export const deepClone = data => {
  var type = getObjType(data)
  var obj
  if (type === 'array') {
    obj = []
  } else if (type === 'object') {
    obj = {}
  } else {
    // 不再具有下一层次
    return data
  }
  if (type === 'array') {
    for (var i = 0, len = data.length; i < len; i++) {
      obj.push(deepClone(data[i]))
    }
  } else if (type === 'object') {
    for (var key in data) {
      obj[key] = deepClone(data[key])
    }
  }
  return obj
}

/**
* 判断是否为空
*/
export const isNull = function (val) {
  if (typeof val === 'boolean') {
    return false
  }
  if (typeof val === 'number') {
    return false
  }
  if (val instanceof Array) {
    if (val.length === 0) return true
  } else if (val instanceof Object) {
    if (JSON.stringify(val) === '{}') return true
  } else {
    if (val === 'null' || val === null || val === 'undefined' || val === undefined || val === '') return true
    return false
  }
  return false
}
/**
* 解析出所有的太监节点id
* @param json 待解析的json串
* @param idArr 原始节点数组
* @param temp 临时存放节点id的数组
* @return 太监节点id数组
*/
export const resolveAllEunuchNodeId = function (json, idArr, temp) {
  for (let i = 0; i < json.length; i++) {
    const item = json[i]
    // 存在子节点，递归遍历;不存在子节点，将json的id添加到临时数组中
    if (item.children && item.children.length !== 0) {
      resolveAllEunuchNodeId(item.children, idArr, temp)
    } else {
      temp.push(idArr.filter(id => isNaN(id) ? id : Number(id) === item.id))
    }
  }
  return temp
}
// 1. 若小于10，前面加0
export const isZero = function (m) {
  return m < 10 ? '0' + m : m
}
// 日期格式化
export const formatDate = function (date) {
  const time = new Date(date)
  const y = time.getFullYear()
  const m = time.getMonth() + 1
  const d = time.getDate()
  const h = time.getHours()
  const mm = time.getMinutes()
  const s = time.getSeconds()

  const params = {
    date: y + '-' + isZero(m) + '-' + isZero(d) + ' ' + isZero(h) + ':' + isZero(mm) + ':' + isZero(s),
    y: y,
    m: isZero(m),
    d: isZero(d),
    h: isZero(h),
    mm: isZero(mm),
    s: isZero(s)
  }
  return params
}

/**
 * 生成随机len位数字
 */
export const randomLenNum = (len, date) => {
  let random = ''
  random = Math.ceil(Math.random() * 100000000000000).toString().substr(0, len || 4)
  if (date) random = random + Date.now()
  return random
}

// 压缩图片
export const compressImage = (file, size, quality) => {
  const img = new Image()
  img.src = file.content
  return new Promise((resolve, reject) => {
    img.onload = function () {
      const canvas = document.createElement('canvas')
      const context = canvas.getContext('2d')
      const originWidth = this.width // 原始宽
      const originHeight = this.height // 原始高
      // 最大尺寸限制，可通过设置宽高来实现图片压缩程度
      const maxWidth = 1200
      const maxHeight = 1200
      let targetWidth = originWidth
      let targetHeight = originHeight
      if (originWidth > maxWidth || originHeight > maxHeight) {
        if (originWidth / originHeight > maxWidth / maxHeight) {
          // 更宽，按照宽度限定尺寸
          targetWidth = maxWidth
          targetHeight = Math.round(maxHeight * (originHeight / originWidth))
        } else {
          targetHeight = maxHeight
          targetWidth = Math.round(maxWidth * (originWidth / originHeight))
        }
      }
      // let targetWidth =  parseInt(originWidth / size)
      // let targetHeight = parseInt(originHeight / size)
      canvas.width = targetWidth
      canvas.height = targetHeight
      context.clearRect(0, 0, targetWidth, targetHeight)
      context.drawImage(img, 0, 0, targetWidth, targetHeight)
      const base64 = canvas.toDataURL('image/jpeg', quality)
      const blob = dataURLtoBlob(base64)
      const asfile = blobToFile(blob, file.file.name)
      var aafile = new File([asfile], file.file.name, { type: file.file.type })
      resolve(aafile)
    }
    img.onerror = (err) => {
      reject(err)
    }
  })
}
const dataURLtoBlob = (dataurl) => {
  const arr = dataurl.split(',')
  const mime = arr[0].match(/:(.*?);/)[1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)

  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], { type: mime })
}
const blobToFile = (theBlob, fileName) => {
  theBlob.lastModifiedDate = new Date()
  theBlob.name = fileName
  return theBlob
}
